package com.iwords.android;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Looper;
import android.widget.Toast;

public class ProgressingActivity extends Activity {


	IWordsApp iWordsApp;
	WordsQueueManager wordsQueueManager;
	boolean created = false;
	protected void onCreate(Bundle icicle) {
		super.onCreate(icicle);

		setContentView(R.layout.progressing);
		//System.out.println("************ProgressingActivity.onCreate() created="+created+" currentLibId = "+getIntent().getLongExtra("currentLibId", 0L));
		created = true;
		// Start lengthy operation in a background thread
		new Thread(new Runnable() {
			public void run() {
				if(doWork()){
					startShowWord();
				}
			}
		}).start();
	}

	public boolean doWork() {
		this.iWordsApp = ((IWordsApp) getApplicationContext());
		this.wordsQueueManager = WordsQueueManager.getInstance();
		this.wordsQueueManager.setIWordsApp(iWordsApp);
		this.wordsQueueManager.setActivity(this);
		this.wordsQueueManager.setCurrentLibId(getIntent().getLongExtra("currentLibId", 0L));
		//System.out.println("************ProgressingActivity.doWork() currentLibId = "+getIntent().getLongExtra("currentLibId", 0L));
		try{
			return this.wordsQueueManager.loadStatus();
		} catch(NeedPayException ne){
			Intent intent = new Intent(this, com.iwords.android.AlipayActivity.class);
			this.startActivity(intent);
		} catch (Exception e) {
			this.displayMessage(e.getMessage());
		}
		return false;
	}

	public void startShowWord() {
		if(neverShowAgain()){
			Intent intent = new Intent(this, ShowWord.class);
			this.startActivity(intent);
		}else{
			Intent intent = new Intent(this, GuideShowWord.class);
			this.startActivity(intent);
		}
	}
	private boolean neverShowAgain() {
		SharedPreferences settings = getSharedPreferences(GuideShowWord.class
				.getName(), MODE_PRIVATE);
		boolean neverShowAgain = settings.getBoolean("neverShowAgain", false);
		//System.out.println("GuideShowWord.neverShowAgain() autologin = "+neverShowAgain);
		return neverShowAgain;
	}

	private void displayMessage(String message) {
		Looper.prepare();
		Toast t1 = Toast.makeText(iWordsApp, message, Toast.LENGTH_LONG);
		t1.show();
	}
	
	public void onResume() {
		super.onResume(); 
		com.mobclick.android.MobclickAgent.onResume(this);
	}
	
	public void onPause() {
		super.onPause(); 
		com.mobclick.android.MobclickAgent.onPause(this);
		this.finish();
	}

}
